<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Warehouse\Controllers;

use App\Eloquent\Ygt\BuyersAddress;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Order;
use App\Eloquent\Ygt\Warehouse;
use App\Eloquent\Ygt\WarehouseOut;
use App\Eloquent\Ygt\WarehouseOutRelation;
use App\Eloquent\Ygt\WarehouseSend;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class SendController extends Controller
{
    public $userId          = 25;
    //生成出货单
    public function edit()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $relationIdStr      = request('relation_id','');
        if( !$userInfo || !$relationIdStr || $relationIdStr==',')
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $nowTime            = $_SERVER['REQUEST_TIME'];
        //出库单详情相关数据
        $relationIdArr      = explode(',',$relationIdStr);
        $where              = ['id'=>['in',$relationIdArr]];
        $relationCollection = WarehouseOutRelation::getList($where);
        if($relationCollection->isEmpty())
        {
            xThrow(ERR_UNKNOWN);
        }
        $relationList       = $relationCollection->toArray();

        //入库单相关信息
        $warehouseIdArr     = $relationCollection->pluck('warehouse_id')->all();
        $where              = ['id'=>['in',$warehouseIdArr]];
        $orderColletion     = Warehouse::getList($where);
        $orderList          = $orderColletion->toArray();
        //工单相关信息,工单地址相关信息
        $orderIdArr         = $relationCollection->pluck('order_id');
        $orderCol           = Order::whereIn('id',$orderIdArr)->get();
        $buyersAddressIdArr = $orderCol->pluck('field_name_22')->all();
        $buyersIdArr        = $orderCol->pluck('field_name_23','id')->all();
        $where              = ['id'=>['in',$buyersAddressIdArr]];
        $buyersAddressList  = BuyersAddress::getList($where)->toArray();
        //入库-------开始
        $sn                 = \App\Engine\Sn::createWarehouseSendSn();
        $data               = [
            'user_id'=>$userId,
            'company_id'=>$companyId,
            'sn'=>$sn,
        ];
        $sendId              = WarehouseSend::insertOneData($data,'id');
        if(!$sendId)
        {
            xThrow(ERR_UNKNOWN);
        }
        $arr            = [
            'created_at'=> $nowTime,
            'updated_at'=> $nowTime,
            'company_id'=> $companyId,
            'user_id'=> $userId,
            'warehouse_send_id'=> $sendId,
        ];

        $warehouseBillIdList = [];//相关交货单ID
        $numberAll = 0;//总数量
        $finishedWeightAll = 0;//总重量
        $packagesAll = 0;//总件数
        foreach($relationList as $key=>$val)
        {
            $valOrderId                     = $val['order_id'];
            $arr['warehouse_out_id']     = $val['warehouse_out_id'];
            $arr['out_relation_id']     = $val['id'];
            $arr['warehouse_id']     = $val['warehouse_id'];
            $arr['customer_id']     = $val['customer_id'];
            $arr['order_id']     = $val['order_id'];
            $arr['number']     = $val['number'];
            $arr['price']     = $val['price'];
            $arr['money']     = $val['money'];
            $arr['packages']     = $val['packages'];
            $arr['buyers_name']     = \App\Engine\Customer::getNameById($val['customer_id']);
            $warehouseBillIdList[] = $val['warehouse_bill_id'];

            //获取成品重量
            $finishedWeight = 0;
            $tmpOrderRow = \App\Eloquent\Ygt\Order::where(['id'=>$val['order_id']])->first();
            if($tmpOrderRow && $tmpOrderRow['finished_weight']){
                $finishedWeight = $tmpOrderRow['finished_weight'];
                $finishedWeightAll += $finishedWeight*$val['number'];//统计总重量
            }


            $numberAll += $val['number'];//统计总数量
            $packagesAll += $val['packages'];//统计总件数


            $provinceId     = $cityId = $areaId = 0;
            $provinceName   = $cityName = $areaName = $address = '';
            $buyersId       = 0;
            if(isset($buyersIdArr[$valOrderId]))
            {
                $buyersId   = $buyersIdArr[$valOrderId];
            }
            foreach($buyersAddressList as $k=>$v)
            {
                if($buyersId!=0 && $v['buyers_id'])
                {
                    $provinceId = $v['province_id'];
                    $cityId = $v['city_id'];
                    $areaId = $v['area_id'];
                    $provinceName = $v['province_name'];
                    $cityName = $v['city_name'];
                    $areaName = $v['area_name'];
                    $address = $v['address'];
                }
            }
            $arr['province_id']     = $provinceId;
            $arr['city_id']         = $cityId;
            $arr['area_id']         = $areaId;
            $arr['province_name']   = $provinceName;
            $arr['city_name']       = $cityName;
            $arr['area_name']       = $areaName;
            $arr['address']         = $address;
            $dataAll[]              = $arr;
        }
        \DB::table('ygt_warehouse_send_relation')->insert($dataAll);
        //更新相关的出库单的处理状态
        $outIdArr               = [];
        foreach($relationList as $key=>$val)
        {
            $outIdArr[]         = $val['warehouse_out_id'];
        }
        $tempData               = ['deal_status'=>1];
        WarehouseOut::whereIn('id',$outIdArr)->update($tempData);
        //入库-------结束
        //app界面需要的内容-------------------开始
        $relationListChange = WarehouseOut::changeRealtionData($relationList,$orderList);
        $addressArr         = [];
        if(!empty($relationListChange))
        {
            $addressAddress = $relationListChange[0]['province_name'];
            $addressAddress .= $relationListChange[0]['city_name'];
            $addressAddress .= $relationListChange[0]['area_name'];
            $addressAddress .= $relationListChange[0]['address'];
            $addressArr     = [
                'province_id'=>$relationListChange[0]['province_id'],
                'city_id'=>$relationListChange[0]['city_id'],
                'area_id'=>$relationListChange[0]['area_id'],
                'province_name'=>$relationListChange[0]['province_name'],
                'city_name'=>$relationListChange[0]['city_name'],
                'area_name'=>$relationListChange[0]['area_name'],
                'address'=>$relationListChange[0]['address'],
                'address_address'=>$addressAddress,
            ];
        }
        $relationListChange = collect($relationListChange)->groupby('field_name_23')->toArray();
        $relationListArr    = [];
        foreach($relationListChange as $key=>$val)
        {

            foreach ($val as $tmpKey => $tmpValue){
                $val[$tmpKey]['weight'] = \App\Engine\Common::fieldDataDeal($val[$tmpKey]['weight'],1);//数据格式调整
            }


            $temp               = [
                'field_name_23'=>$key,
                'data'=>$val,
            ];
            $relationListArr[]  = $temp;
        }
        $where              = ['id'=>$sendId];
        $sendInfo           = WarehouseSend::getInfo($where);
        if(!$sendInfo)
        {
            xThrow(ERR_UNKNOWN);
        }
        $sendArr            = $sendInfo->toArray();
        $send               = [
            'id'=>$sendId,
            'sn'=>$sendArr['sn'],
            'created_at'=>date('Y-m-d H:i:s',$sendArr['created_at']),
        ];
        //app界面需要的内容-------------------结束

        //增加默认的重量和件数

        //修改对应的交货单状态改为发货员发货 zhuyujun 20181227
        if(!empty($warehouseBillIdList)){
            $tmpWarehouseBillList = \App\Eloquent\Ygt\WarehouseBill::whereIn('id',$warehouseBillIdList)->get();
            foreach($tmpWarehouseBillList as $tmpWarehouseBillRow){
                $tmpWarehouseBillRow->status = 3;
                $tmpWarehouseBillRow->save();
            }
        }

        $finishedWeightAll = \App\Engine\Common::weightDeal($finishedWeightAll);//重量数据处理

        $result         = [
            'out_list'=>$relationListArr,
            'address'=>$addressArr,
            'send_info'=>$send,
            'number_all'=>$numberAll,
            'packages_all'=>$packagesAll,
            'finished_weight_all'=>$finishedWeightAll,
        ];
        return $result;
    }

    //返回对应的物流信息
    public function getLogisticsDetail(){
        $warehouseSendId = request('warehouse_send_id');

        //获取地址信息
        //app界面需要的内容-------------------开始

        $relationIdArr = \App\Eloquent\Ygt\WarehouseSendRelation::where(['warehouse_send_id'=>$warehouseSendId])->get()->pluck('out_relation_id');
        $where              = ['id'=>['in',$relationIdArr]];
        $relationCollection = WarehouseOutRelation::getList($where);

        if($relationCollection->isEmpty())
        {
            xThrow(ERR_UNKNOWN);
        }
        $relationList       = $relationCollection->toArray();

        $numberAll = 0;//总数量
        $finishedWeightAll = 0;//总重量
        $packagesAll = 0;//总件数
        foreach($relationList as $key=>$val) {
            //获取成品重量
            $finishedWeight = 0;
            $tmpOrderRow = \App\Eloquent\Ygt\Order::where(['id' => $val['order_id']])->first();
            if ($tmpOrderRow && $tmpOrderRow['finished_weight']) {
                $finishedWeight = $tmpOrderRow['finished_weight'];
                $finishedWeightAll += $finishedWeight * $val['number'];//统计总重量
            }

            $numberAll += $val['number'];//统计总数量
            $packagesAll += $val['packages'];//统计总件数
        }

        //入库单相关信息
        $warehouseIdArr     = $relationCollection->pluck('warehouse_id')->all();
        $where              = ['id'=>['in',$warehouseIdArr]];
        $orderColletion     = Warehouse::getList($where);
        $orderList          = $orderColletion->toArray();

        $relationListChange = WarehouseOut::changeRealtionData($relationList,$orderList);
        $addressArr         = [];
        if(!empty($relationListChange))
        {
            $addressAddress = $relationListChange[0]['province_name'];
            $addressAddress .= $relationListChange[0]['city_name'];
            $addressAddress .= $relationListChange[0]['area_name'];
            $addressAddress .= $relationListChange[0]['address'];
            $addressArr     = [
                'province_id'=>$relationListChange[0]['province_id'],
                'city_id'=>$relationListChange[0]['city_id'],
                'area_id'=>$relationListChange[0]['area_id'],
                'province_name'=>$relationListChange[0]['province_name'],
                'city_name'=>$relationListChange[0]['city_name'],
                'area_name'=>$relationListChange[0]['area_name'],
                'address'=>$relationListChange[0]['address'],
                'address_address'=>$addressAddress,
            ];
        }

        //读取出库单中的重量和件数

        $finishedWeightAll = \App\Engine\Common::weightDeal($finishedWeightAll);//重量数据处理

        return [
            'address'=>$addressArr,
            'warehouse_send_id' => $warehouseSendId,
            'number_all'=>$numberAll,
            'packages_all'=>$packagesAll,
            'finished_weight_all'=>$finishedWeightAll,
        ];
    }




}